package com.njtoyo.taxi.admin.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class SignUtil {
    public static boolean checkSign(CCBaseEntity CCBaseEntity, String key) {
        Long timestamp = CCBaseEntity.getTimestamp();
        // 1、检查 timestamp 是否超出允许的范围（此处假定最大允许15分钟差距）
        long timestampDisparity = System.currentTimeMillis() - timestamp; // 实际的时间差
        if(timestampDisparity > 1000 * 60 * 15) {
            log.error("sign:{},时间差超出允许的范围，请求无效", CCBaseEntity);
            return false;
        }
        String sign = CCBaseEntity.getSign();
        String genSign = genSign(CCBaseEntity, key);
        log.info("baseEntity:{},key{},genSign{}", CCBaseEntity,key,genSign);

        return Objects.equals(genSign,sign);
    }
    public static String genSign(CCBaseEntity CCBaseEntity, String key) {
        Map<String, Object> param = BeanUtil.beanToMap(CCBaseEntity);
        param.put("sign_key", key);
        param.remove("sign");
        param.remove("extInfo");

        List<Map.Entry<String, Object>> infoIds = new ArrayList<>(param.entrySet());
        Collections.sort(infoIds, Comparator.comparing(Map.Entry<String, Object>::getKey));

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : infoIds) {
            if(!Objects.isNull(entry.getValue()))
                sb.append(entry.getKey()).append(entry.getValue());
        }

        return DigestUtil.md5Hex(sb.toString());
    }

}
